<?php 

/*自定义表单*/

namespace app\admin\controller;
use app\admin\service\FormDataService;
use app\admin\db\Field;
use xhadmin\db\Extend;
use think\facade\Cache;
use xhadmin\db\BaseDb;

class FormData extends Admin {

	
	/*数据列表*/
	function index(){
		$extend_id = $this->request->param('extend_id', '', 'strval');
		!$extend_id && $this->error('参数错误');
		
		if (!$this->request->isAjax()){
			$fieldList =  Field::loadList(['extend_id'=>$extend_id,'status'=>1,'list_show'=>1]);
			$searchList = Field::loadList(['extend_id'=>$extend_id,'status'=>1,'is_search'=>1]);
			
			$this->view->assign('extendInfo',Extend::getInfo($extend_id));
			$this->view->assign('formStr',FormDataService::getTableList($fieldList));
			$this->view->assign('searchGroup',FormDataService::getSearchGroup($searchList));
			$this->view->assign('queryParam',FormDataService::getQueryParam($searchList));
			$this->view->assign('extend_id',$extend_id);
			return $this->display('form_data/index');
		}else{
			$limit  = input('post.limit', 0, 'intval');
			$offset = input('post.offset', 0, 'intval');
			$page   = floor($offset / $limit) +1 ;
			
			$limit = ($page-1) * $limit.','.$limit;
			try{
				$where= [];
				$searchList = Field::loadList(['extend_id'=>$extend_id,'status'=>1,'is_search'=>1]);
				if($searchList){
					foreach($searchList as $k=>$v){
						if($v['type'] == 12){
							$startTime = input('param.startTime', '', 'strip_tags');
							$endTime = input('param.endTime', '', 'strip_tags');
							$where[$v['field']] = \xhadmin\CommonService::getTimeWhere($startTime,$endTime);
						}else if($v['type'] == 17){
							foreach(explode('|',$v['field']) as $m=>$n){
								$where[$n] = input('param.'.$n.'', '', 'strip_tags');
							}
						}else{
							$where[$v['field']] = ['like',input('param.'.$v['field'].'', '', 'strip_tags')];
						}	
					}
				}
				$extendInfo = Extend::getInfo($extend_id);
				if($extendInfo['orderby']){
					$orderby = $extendInfo['orderby']; 
				}else{
					$orderby = 'data_id desc';
				}
				$res = FormDataService::loadList(formatWhere($where),$field='*',$limit,$extend_id,$orderby);
			}catch(\Exception $e){
				exit($e->getMessage());
			}
			$list = $res['list'];
			$data['rows']  = $list;
			$data['total'] = $res['count'];

			exit(json_encode($data));
		}
	}
	
	/*删除数据*/
	function delete(){
		$idx = $this->request->param('data_ids', '', 'strval');
		$extend_id = $this->request->param('extend_id', '', 'strval');
		if(empty($idx) || empty($extend_id)){
			return json(['status'=>'01','msg'=>'参数错误']);
		}
		try{
			$where = [];
			$where['data_id'] =explode(',',$idx);
			$res = FormDataService::delete($where,$extend_id);
		}catch(\Exception $e){
			exit(json_encode(array('status'=>'02','msg'=>$e->getMessage())));
		}
		return json(['status'=>'00','msg'=>'操作成功']);
	}
	
	
	/*创建数据*/
	function add(){
		if (!$this->request->isPost()){
			$extend_id = $this->request->param('extend_id','','intval');
			if(empty($extend_id)){
				return json(['status'=>'01','msg'=>'参数错误']);
			}
			$htmlstr = '';
			$fieldList = Field::loadList(['extend_id'=>$extend_id,'status'=>1]);
			!$fieldList && $this->error('没有拓展信息');
			foreach($fieldList as $key=>$val){
				$htmlstr .= \app\admin\service\FieldService::getFieldData($val);
			}
			$this->view->assign('extend_id',$extend_id);
			$this->view->assign('formStr',$htmlstr);
			return $this->display('form_data/info');
		}else{
			$data = $this->request->post();
			try {
				$fieldList = Field::loadList(['extend_id'=>$data['extend_id'],'status'=>1]);
				!$fieldList && $this->error('没有拓展信息');
				$res = FormDataService::saveData('add',$data,$fieldList);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'操作成功']);
		}
	}
	
	/*修改数据*/
	function update(){
		if (!$this->request->isPost()){
			$extend_id =  $this->request->param('extend_id','','intval');
			$data_id =  $this->request->param('data_id','','intval');
			if(empty($extend_id) || empty($data_id)){
				return json(['status'=>'01','msg'=>'参数错误']);
			}
			
			$extFormInfo = FormDataService::getInfo($extend_id,$data_id);
			$htmlstr = '';
			$fieldList = Field::loadList(['extend_id'=>$extend_id,'status'=>1]);
			foreach($fieldList as $key=>$val){
				if($val['type'] == 17){
					$areaVal = explode('|',$val['field']);
					$val['province'] = $extFormInfo[$areaVal[0]];
					$val['city'] = $extFormInfo[$areaVal[1]];
					$val['district'] = $extFormInfo[$areaVal[2]];
				}else{
					$val['value'] = $extFormInfo[$val['field']];
				}
				
				$val['data_id'] = $data_id;

				$htmlstr .= \app\admin\service\FieldService::getFieldData($val);
					
			}
			$this->view->assign('data_id',$data_id);
			$this->view->assign('extend_id',$extend_id);
			$this->view->assign('formStr',$htmlstr);
			$this->assign('fieldList',$fieldList);
			return $this->display('form_data/info');
		}else{
			$data = $this->request->post();
			try {
				$fieldList = Field::loadList(['extend_id'=>$data['extend_id'],'status'=>1]);
				$res = FormDataService::saveData('edit',$data,$fieldList);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'操作成功']);
		}
	}
	
	//查看数据方法
	public function view(){
		$extend_id =  $this->request->param('extend_id','','intval');
		$data_id =  $this->request->param('data_id','','intval');
		if(empty($extend_id) || empty($data_id)){
			return json(['status'=>'01','msg'=>'参数错误']);
		} 
		$extFormInfo = FormDataService::getInfo($extend_id,$data_id);
		
		$fieldList = Field::loadList(['extend_id'=>$extend_id,'status'=>1]);
		foreach($fieldList as $key=>$val){	
			if($val['type'] == 17){
				$areaVal = explode('|',$val['field']);
				$fieldList[$key]['province'] = $extFormInfo[$areaVal[0]];
				$fieldList[$key]['city'] = $extFormInfo[$areaVal[1]];
				$fieldList[$key]['district'] = $extFormInfo[$areaVal[2]];
			}else{
				$fieldList[$key]['value'] = $extFormInfo[$val['field']];
			}
			$fieldList[$key]['value'] = $extFormInfo[$val['field']];		
		}
		$this->view->assign('formStr',FormDataService::getView($fieldList));
		return $this->display('form_data/view');
	}
	
	
	//数据导出
	public function dumpData(){
		$data = input('param.');
		empty($data['extend_id']) && $this->error('模块ID不能为空');
		try {
			//此处读取前端传过来的 表格勾选的显示字段
			$fieldInfo = [];
			for($j=0; $j<100;$j++){
				$fieldInfo[] = $this->request->param($j);
			}
			$fieldInfo = \xhadmin\CommonService::filterEmptyArray($fieldInfo);
			$res = FormDataService::dumpData($data,array_unique($fieldInfo));
		} catch (\Exception $e) {
			$this->error($e->getMessage());
		}
	}
	
	//数据导入
	public function importData(){
		if ($this->request->isPost()) {
			try{
				$extend_id = $this->request->param('extend_id','','intval');
				$key = 'formData:'.$extend_id;
				$result = \xhadmin\CommonService::importData($key);
				if (count($result) > 0) {
					Cache::set($key,$result,3600);
					return redirect(url('startImport',['extend_id'=>$extend_id]));
				} else{
					$this->error('内容格式有误！');
				}
			}catch(\Exception $e){
				$this->error($e->getMessage());
			}
		}else {
			return $this->display('base/importData');
		}
	}
	
	
	//开始导入
	function startImport(){
		if(!$this->request->isPost()) {
			$extend_id = $this->request->param('extend_id','','intval');
			$this->view->assign('extend_id',$extend_id);
			return $this->display('base/startImport');
		}else{
			$p = $this->request->post('p', '', 'intval'); 
			$extend_id = $this->request->param('extend_id','','intval');
			$data = Cache::get('formData:'.$extend_id);
			$export_per_num = config('my.export_per_num') ? config('my.export_per_num') : 50;
			$num = ceil((count($data)-1)/$export_per_num);
			if($data){
				$start = $p == 1 ? 2 : ($p-1) * $export_per_num + 1;
				if($data[$start]){
					$dt['percent'] = ceil(($p)/$num*100);
					try{
						for($i=1; $i<=$export_per_num; $i++ ){
						//根据中文名称来读取字段名称
							if($data[$i + ($p-1)*$export_per_num]){
								foreach($data[1] as $key=>$val){
									$fieldInfo = \app\admin\db\Field::getWhereInfo(['name'=>$val,'extend_id'=>$extend_id]);
									if($val && $fieldInfo){
									$d[$fieldInfo['field']] = $data[$i + ($p-1)*$export_per_num][$key];
									if($fieldInfo['type'] == 17){
										unset($d[$fieldInfo['field']]);
									}
									if(in_array($fieldInfo['type'],[7,12])){	//时间字段
										$d[$fieldInfo['field']] = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($data[$i + ($p-1)*$export_per_num][$key]);
									}
									if($fieldInfo['type'] == 5){	//密码字段
										$d[$fieldInfo['field']] = md5($data[$i + ($p-1)*$export_per_num][$key].config('my.password_secrect'));
									}
									if($fieldInfo['type'] == 17){	//三级联动字段
										$arrTitle = explode('|',$fieldInfo['field']);
										$arrValue = explode('-',$data[$i + ($p-1)*$export_per_num][$key]);
										if($arrTitle && $arrValue){
											foreach($arrTitle as $k=>$v){
												$d[$v] = $arrValue[$k];
											}
										}
									}
									if(in_array($fieldInfo['type'],[2,3,23])){	//下拉，单选，开关按钮
										$d[$fieldInfo['field']] = getFieldName($data[$i + ($p-1)*$export_per_num][$key],$fieldInfo['config']);
									}
									}
								}
								$d['create_time'] = time();
								if(($i + ($p-1)*$export_per_num) > 1){
									$extendInfo = Extend::getInfo($extend_id);
									BaseDb::setTableName(config('my.create_table_pre').$extendInfo['table_name']);
									BaseDb::setPk('data_id');
									BaseDb::createData($d);
								}
							}
						}
					}catch(\Exception $e){
						return json(['error'=>'01','msg'=>$e->getMessage()]);
					}
					return json(['error'=>'00','data'=>$dt]);
				}else{
					Cache::delete('formData:'.$extend_id);
					return json(['error'=>'10']);
				}
			}else{
				$this->error('当前没有数据');
			}
		}
	}
	
	/*获取拓展字段信息*/
	public function getExtends(){
		$extend_id =  input('param.extend_id','','intval');
		$fieldList =  Field::loadList(['extend_id'=>$extend_id,'status'=>1]);
		echo json_encode($fieldList);
	}
	

	

}